/**
  ******************************************************************************
  * @file    dev_time.h
  * @brief
  * @author  zp
  * @version V1.0.0
  * @date    2024/01/29
  ******************************************************************************
  */


/* Includes ------------------------------------------------------------------*/

/* Bsp includes. */
#include "string.h"

/* Os includes. */

/* User includes. */
#include "dev_time.h"


/* Public macro --------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/

/* Type defines --------------------------------------------------------------*/

/* Const defines -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

/* Private Enum --------------------------------------------------------------*/

/* Private Union -------------------------------------------------------------*/

/* Private Struct ------------------------------------------------------------*/
dev_time_t dev_time;

/* Macros (Inline Functions) Definitions -------------------------------------*/
static void local_tick_inc(dev_time_t* dev);
static void gettimeofday(dev_time_t* dev, timedate_t* td);
static void time(dev_time_t* dev, timeval_t* tv);

/* Pubilc function prototypes ------------------------------------------------*/

int DevTime_Init(void)
{
	dev_time.local_ticks = 0;
	memset(&dev_time.time, 0, sizeof(dev_time.time));
	
	dev_time.sec2tick = 1000;
		
	dev_time.local_tick_inc = local_tick_inc;
	dev_time.time = time;
	dev_time.gettimeofday = gettimeofday;
	
	return 0;
}

static void local_tick_inc(dev_time_t* dev)
{
	dev->local_ticks++;
}

static void gettimeofday(dev_time_t* dev, timedate_t* td)
{
	timeval_t tv;
	time(dev, &tv);
	
	td->day =    tv.second/(3600*24);
	td->hour =   tv.second%(3600*24)/3600;
	td->min =    tv.second%(3600*24)%3600/60;
	td->second = tv.second%(3600*24)%3600%60;
}

static void time(dev_time_t* dev, timeval_t* tv)
{
	tv->second = dev->local_ticks/dev_time.sec2tick;
	tv->msecond = dev->local_ticks%dev_time.sec2tick;
}


